package wang.jinggo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * http请求工具类
 */
public class HttpRequestUtils {

    private static final Logger LOG = LoggerFactory.getLogger(HttpRequestUtils.class);    //日志记录
    
    private static final int READ_TIME_OUT = 30000;//30秒
    
    private static final int CONNECT_TIME_OUT = 30000;//30秒

    /**
     * http get请求
     * @param path 请求url
     * @return 请求结果
     */
    public static String httpGet(String path){
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            URL url = new URL(path.trim());
            //打开连接
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(CONNECT_TIME_OUT);
            urlConnection.setReadTimeout(READ_TIME_OUT);
            LOG.info("responseCode: " + urlConnection.getResponseCode());
            LOG.info("responseMessage: " + urlConnection.getResponseMessage());
            if (HttpStatus.OK.value() == urlConnection.getResponseCode()){
                //得到输入流
                is = urlConnection.getInputStream();
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while (-1 != (len = is.read(buffer))){
                    baos.write(buffer, 0, len);
                    baos.flush();
                }
                String result = baos.toString("utf-8");
                LOG.info("请求返回数据: " + result);
                is.close();
                baos.close();
                return result;
            }
        }catch (IOException e){
            LOG.error("httpGet请求失败", e);
        } finally {
            if (is != null){
                try {
                    is.close();
                }catch (IOException e){
                    LOG.error("关闭输入流失败: ", e);
                }
            }
            if (baos != null){
                try {
                    baos.close();
                }catch (IOException e){
                    LOG.error("关闭输出流失败: ", e);
                }
            }
        }
        return null;
    }

    /**
     * http post表单提交请求
     * @param path 请求url
     * @param post 表单提交数据(eg: xx=xx&yy=yy)
     * @return
     */
    public static String httpPost (String path, String post){
        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = null;
        PrintWriter printWriter = null;
        try {
            URL url = new URL(path);
            //打开连接
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST"); //提交模式
            urlConnection.setConnectTimeout(CONNECT_TIME_OUT);
            urlConnection.setReadTimeout(READ_TIME_OUT);
            //post请求必须设置如下两行
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            //获取输出流
            printWriter = new PrintWriter(urlConnection.getOutputStream());
            //发送请求参数
            printWriter.write(post);
            //flush输出流的缓冲
            printWriter.flush();
            printWriter.close();
            LOG.info("responseCode: " + urlConnection.getResponseCode());
            LOG.info("responseMessage: " + urlConnection.getResponseMessage());
            if (HttpStatus.OK.value() == urlConnection.getResponseCode()) {
                //开始获取数据
                bis = new BufferedInputStream(urlConnection.getInputStream());
                bos = new ByteArrayOutputStream();
                int len;
                byte[] arr = new byte[1024];
                while (-1 != (len = bis.read(arr))) {
                    bos.write(arr, 0, len);
                    bos.flush();
                }
                String result = bos.toString("utf-8");
                LOG.info("请求返回数据: " + result);
                bis.close();
                bos.close();
                return result;
            }
        }catch (IOException e){
            LOG.error("httpPost请求失败", e);
        }finally {
            if (printWriter != null){
                printWriter.close();
            }
            if (bis != null){
                try {
                    bis.close();
                }catch (IOException e){
                    LOG.error("关闭输入流失败: ", e);
                }
            }
            if (bos != null){
                try {
                    bos.close();
                }catch (IOException e){
                    LOG.error("关闭输出流失败: ", e);
                }
            }
        }
        return null;
    }

    /**
     * http post提交json
     * @param path 请求url
     * @param json 提交json
     * @return
     */
    public static String httpPostJson (String path, String json){
        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = null;
        OutputStream os = null;
        try {
            URL url = new URL(path);
            //打开连接
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST"); //提交模式
            urlConnection.setConnectTimeout(CONNECT_TIME_OUT);
            urlConnection.setReadTimeout(READ_TIME_OUT);
            //post请求必须设置如下两行
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            //设置不用缓存
            urlConnection.setUseCaches(false);
            //设置文件字符集
            urlConnection.setRequestProperty("Charset", "UTF-8");
            //转换为字节数组
            byte[] data = (json).getBytes();
            //设置文件长度
            urlConnection.setRequestProperty("Content-length", String.valueOf(data.length));
            //设置文件类型
            urlConnection.setRequestProperty("connection", "keep-alive");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            //获取输出流
            os = urlConnection.getOutputStream();
            //发送请求参数
            os.write(data);
            //flush输出流的缓冲
            os.flush();
            os.close();
            LOG.info("responseCode: " + urlConnection.getResponseCode());
            LOG.info("responseMessage: " + urlConnection.getResponseMessage());
            if (HttpStatus.OK.value() == urlConnection.getResponseCode()) {
                //开始获取数据
                bis = new BufferedInputStream(urlConnection.getInputStream());
                bos = new ByteArrayOutputStream();
                int len;
                byte[] arr = new byte[1024];
                while (-1 != (len = bis.read(arr))) {
                    bos.write(arr, 0, len);
                    bos.flush();
                }
                String result = bos.toString("utf-8");
                LOG.info("请求返回数据: " + result);
                bis.close();
                bos.close();
                return result;
            }
        }catch (IOException e){
            LOG.error("httpPostJson请求失败", e);
        }finally {
            if (os != null){
                try {
                    os.close();
                }catch (IOException e){
                    LOG.error("关闭输出流os失败: ", e);
                }
            }
            if (bis != null){
                try {
                    bis.close();
                }catch (IOException e){
                    LOG.error("关闭输入流失败: ", e);
                }
            }
            if (bos != null){
                try {
                    bos.close();
                }catch (IOException e){
                    LOG.error("关闭输出流bos失败: ", e);
                }
            }
        }
        return null;
    }

    /**
     * http post提交json
     * @param path 请求url
     * @param json 提交json
     * @return
     */
    public static String httpPostJsonWithAutho (String path, String json,String uuid){
        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = null;
        OutputStream os = null;
        try {
            URL url = new URL(path);
            //打开连接
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST"); //提交模式
            urlConnection.setConnectTimeout(CONNECT_TIME_OUT);
            urlConnection.setReadTimeout(READ_TIME_OUT);
            //post请求必须设置如下两行
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            //设置不用缓存
            urlConnection.setUseCaches(false);
            //设置文件字符集
            urlConnection.setRequestProperty("Charset", "UTF-8");
            //转换为字节数组
            byte[] data = (json).getBytes();
            //设置文件长度
            urlConnection.setRequestProperty("Content-length", String.valueOf(data.length));
            //设置文件类型
            urlConnection.setRequestProperty("connection", "keep-alive");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Authorization",uuid);
            //获取输出流
            os = urlConnection.getOutputStream();
            //发送请求参数
            os.write(data);
            //flush输出流的缓冲
            os.flush();
            os.close();
            LOG.info("responseCode: " + urlConnection.getResponseCode());
            LOG.info("responseMessage: " + urlConnection.getResponseMessage());
            if (HttpStatus.OK.value() == urlConnection.getResponseCode()) {
                //开始获取数据
                bis = new BufferedInputStream(urlConnection.getInputStream());
                bos = new ByteArrayOutputStream();
                int len;
                byte[] arr = new byte[1024];
                while (-1 != (len = bis.read(arr))) {
                    bos.write(arr, 0, len);
                    bos.flush();
                }
                String result = bos.toString("utf-8");
                LOG.info("请求返回数据: " + result);
                bis.close();
                bos.close();
                return result;
            }
        }catch (IOException e){
            LOG.error("httpPostJson请求失败", e);
        }finally {
            if (os != null){
                try {
                    os.close();
                }catch (IOException e){
                    LOG.error("关闭输出流os失败: ", e);
                }
            }
            if (bis != null){
                try {
                    bis.close();
                }catch (IOException e){
                    LOG.error("关闭输入流失败: ", e);
                }
            }
            if (bos != null){
                try {
                    bos.close();
                }catch (IOException e){
                    LOG.error("关闭输出流bos失败: ", e);
                }
            }
        }
        return null;
    }

}